﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _05_委托_必要性1
{
    public delegate double DoSomeDelegate(int value1, int value2);
    internal class Program
    {
        static void Main(string[] args)
        {
            int a = 10, b = 20;
            #region 不使用委托的情况

            //double result1 = DoMath(a, b, "+");
            //Console.WriteLine("{0}+{1}={2}", a, b, result1);

            //double result2 = DoMath(a, b, "-");
            //Console.WriteLine("{0}-{1}={2}", a, b, result2);

            //double result3 = DoMath(a, b, "*");
            //Console.WriteLine("{0}*{1}={2}", a, b, result3);

            //double result4 = DoMath(a, b, "/");
            //Console.WriteLine("{0}/{1}={2}", a, b, result4);

            //double result5 = DoMath(a, b, "平方和");
            //Console.WriteLine("{0}*{0}+{1}*{1}={2}", a, b, result5);

            #endregion

            #region 使用委托的情况

            double result1 = DoMath(a, b, new DoSomeDelegate(Add)); //形参当中委托的完整写法
            Console.WriteLine("{0}+{1}={2}", a, b, result1);

            double result2 = DoMath(a, b, Sub); //形参当中委托的简写写法
            Console.WriteLine("{0}-{1}={2}", a, b, result2);

            double result3 = DoMath(a, b, Mul); //形参当中委托的简写写法
            Console.WriteLine("{0}*{1}={2}", a, b, result3);

            double result4 = DoMath(a, b, Div); //形参当中委托的简写写法
            Console.WriteLine("{0}/{1}={2}", a, b, result4);

            double result5 = DoMath(a, b, SquareSum); //形参当中委托的简写写法
            Console.WriteLine("{0}*{0}+{1}*{1}={2}", a, b, result5);
            #endregion

            Console.ReadKey();
        }

        public static double DoMath(int a, int b, string type)
        {
            //计算结果
            double result = 0;
            //Switch判断不同的计算类型
            switch (type)
            {
                case "+": result = Add(a, b); break;
                case "-":  result = Sub(a, b); break;
                case "*": result = Mul(a, b);  break;
                case "/":  result = Div(a, b);  break;
                case "平方和": result = SquareSum(a, b); break;
                default: Console.WriteLine("输入非法字符串，请按要求输入:+、-、*、/"); break;
            }
            //返回计算结果
            return result;
        }

        public static double DoMath(int a, int b, DoSomeDelegate doSomeDelegate)
        {
            return doSomeDelegate.Invoke(a, b);
        }

        public static double Add(int a, int b) {return a + b; }
        public static double Sub(int a, int b) { return a - b; }
        public static double Mul(int a, int b) { return a * b; }
        public static double Div(int a, int b) { return a*1.0 / b; }
        public static double SquareSum(int a, int b) { return a * a + b * b; }

    }
}
